package util;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;

public class ActivityUtil {

	private static final String TAG = "ActivityUtil";

	/**
	 * Launches the given activity.
	 */
	public static void launchActivity(Context ctx,
			Class<? extends Activity> activity) {
		Intent intent = new Intent(ctx, activity);
		ctx.startActivity(intent);
	}

	/**
	 * Launches the given activity with the given extras Bundle.
	 */
	public static void launchActivity(Context ctx,
			Class<? extends Activity> activity, Bundle extras) {
		Intent intent = new Intent(ctx, activity);
		intent.putExtras(extras);
		ctx.startActivity(intent);
	}

	/**
	 * Sets the given ImageView with the image retrieved from the given URL.
	 * Returns true if the image was successfully set, false if not.
	 * 
	 * @param i
	 *            ImageView to set
	 * @param imageUrl
	 *            URL to retrieve image from
	 * @return true if image was successfully set, false if not
	 */
	public static Boolean setImageViewFromUrl(ImageView i, String imageUrl) {
		try {
			Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
					imageUrl).getContent());
			i.setImageBitmap(bitmap);
			Log.i(TAG, "Bitmap " + imageUrl + " retrieved and set");
			return true;
		} catch (MalformedURLException e) {
			Log.w(TAG, "Could not retrieve bitmap image from URL " + imageUrl
					+ " - URL malformed");
			return false;
		} catch (IOException e) {
			Log.w(TAG, "Could not retrieve bitmap image from URL " + imageUrl
					+ " - IOException occurred");
			return false;
		}
	}

}
